package com.liushunqiu.realtor.resolver;

import com.alibaba.fastjson2.JSON;
import com.liushunqiu.realtor.annotation.Param;
import io.vertx.core.MultiMap;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;

public class HttpParamResolver implements ParamResolver {
    private MultiMap httpParams;

    public HttpParamResolver(MultiMap httpParams) {
        this.httpParams = httpParams;
    }

    @Override
    public Object resolve(Method method, int paramIndex) {
        Parameter parameter = method.getParameters()[paramIndex];
        if (parameter.isAnnotationPresent(Param.class)) {
            Param param = parameter.getAnnotation(Param.class);
            return this.httpParams.get(param.value());
        }else if(!parameter.getType().isPrimitive()){
            Map<String, Object> result = new HashMap<>();
            Map<String,List<Object>> repeatMap = new HashMap<>();
            for (Map.Entry<String, String> entry : this.httpParams.entries()) {
                Object data = result.get(entry.getKey());
                if (Objects.isNull(data)){
                    result.put(entry.getKey(),entry.getValue());
                }else{
                    List<Object> repeat = repeatMap.get(entry.getKey());
                    if (Objects.isNull(repeat)){
                        repeat = new ArrayList<>();
                        if (data instanceof List<?>){
                            repeat.addAll((List<?>)data);
                        }else{
                            repeat.add(data);
                        }
                        repeatMap.put(entry.getKey(),repeat);
                    }
                    repeat = repeatMap.get(entry.getKey());
                    repeat.add(entry.getValue());
                    result.put(entry.getKey(),repeat);
                }
            }
            return JSON.parseObject(JSON.toJSONString(result),parameter.getType());
        }
        return null; // or throw exception
    }
}
